package com.charonmc.parkour;

import com.charonmc.CharonHub;
import com.charonmc.events.PlayerAfterLoginListener;
import com.charonmc.utils.mysql.SqlManager;
import lombok.SneakyThrows;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;

import java.sql.ResultSet;
import java.sql.Timestamp;

public class ParkourListener implements Listener {
    @EventHandler
    public void onPlayerMoveIronPlate(PlayerMoveEvent event){
        if (event.getFrom().getBlock().equals(event.getTo().getBlock())){
            return;
        }
        if (event.getTo().getBlock().getType().equals(Material.IRON_PLATE)){
            if (event.getTo().getBlock().getLocation().equals(CharonHub.StartLocation)){
                //开始
                ItemStack bc = new ItemStack(Material.GOLD_PLATE);
                ItemMeta bcIm = bc.getItemMeta();
                bcIm.setDisplayName("§e§l返回记录点");
                bc.setItemMeta(bcIm);
                ItemStack bs = new ItemStack(Material.IRON_PLATE);
                ItemMeta bsIm = bs.getItemMeta();
                bsIm.setDisplayName("§e§l返回起点");
                bs.setItemMeta(bsIm);
                ItemStack end = new ItemStack(Material.REDSTONE_BLOCK);
                ItemMeta endIm = end.getItemMeta();
                endIm.setDisplayName("§c§l退出");
                end.setItemMeta(endIm);
                ParkourManager.parkourPlayers.put(event.getPlayer(), 0);
                ParkourManager.playerLocation.put(event.getPlayer(), event.getTo());
                event.getPlayer().getInventory().clear();
                event.getPlayer().getInventory().setItem(0, bs);
                event.getPlayer().getInventory().setItem(4, bc);
                event.getPlayer().getInventory().setItem(8, end);
                event.getPlayer().sendMessage("§a§l跑酷已开始，加油! §7(你的最佳纪录为：" + CharonHub.getFormat(ParkourManager.getPlayerRecordTick(event.getPlayer()))  + ")");
            } else if (event.getTo().getBlock().getLocation().equals(CharonHub.EndLocation) && ParkourManager.parkourPlayers.containsKey(event.getPlayer())){
                //结束
                if (ParkourManager.getPlayerTimeTick(event.getPlayer()) < ParkourManager.getPlayerRecordTick(event.getPlayer())){
                    event.getPlayer().sendMessage("§a§l跑酷结束，您的成绩为" + CharonHub.getTimeFormat(event.getPlayer()) + "§7(恭喜！新纪录)");
                    ParkourManager.playerParkourRecord.put(event.getPlayer(), ParkourManager.getPlayerTimeTick(event.getPlayer()));
                    BukkitRunnable updateRecord = new BukkitRunnable() {
                        @SneakyThrows
                        @Override
                        public void run() {
                            SqlManager sqlManager = new SqlManager("charonmc");
                            Object id = sqlManager.createQuery()
                                    .inTable("players")
                                    .selectColumns("player_id")
                                    .addCondition("player_name", event.getPlayer().getName())
                                    .build()
                                    .execute()
                                    .first();
                            Timestamp time = new Timestamp(System.currentTimeMillis());
                            sqlManager.createUpdate()
                                    .inTable("parkour_1")
                                    .addColumnNames(new String[]{"time", "score"})
                                    .addParams(new Object[]{time, ParkourManager.getPlayerRecordTick(event.getPlayer())})
                                    .build()
                                    .execute();
                            sqlManager.close();
                        }
                    };
                    updateRecord.runTaskAsynchronously(CharonHub.instance);
                } else {
                    event.getPlayer().sendMessage("§a§l跑酷结束，您的成绩为" + CharonHub.getTimeFormat(event.getPlayer()) + "§7(您的最佳记录为: " + CharonHub.getFormat(ParkourManager.getPlayerRecordTick(event.getPlayer())) + ")");
                }
                CharonHub.setPlayerDefaultInventory(event.getPlayer());
                ParkourManager.parkourPlayers.remove(event.getPlayer());
            }
        }
    }
    @EventHandler
    public void onPlayerMoveGoldPlate(PlayerMoveEvent event) {
        if (event.getFrom().getBlock().equals(event.getTo().getBlock())){
            return;
        }
        if (event.getTo().getBlock().getType().equals(Material.GOLD_PLATE)) {
            if (ParkourManager.parkourPlayers.containsKey(event.getPlayer())){
                //河里
                event.getPlayer().sendMessage("§b§l已为设置记录点");
                ParkourManager.playerLocation.put(event.getPlayer(), event.getTo());
            }
        }
    }

    @EventHandler
    public void onAdminBreakIronPlate(BlockBreakEvent event){
        if (event.getBlock().getType().equals(Material.IRON_PLATE) && ParkourManager.adminSet.containsKey(event.getPlayer())){
            if (ParkourManager.adminSet.get(event.getPlayer()) == 1){
                //放start
                CharonHub.instance.getConfig().set("StartX", event.getBlock().getX());
                CharonHub.instance.getConfig().set("StartY", event.getBlock().getY());
                CharonHub.instance.getConfig().set("StartZ", event.getBlock().getZ());
                CharonHub.instance.saveConfig();
                event.getPlayer().sendMessage("§b§l已设置起点");
                event.setCancelled(true);
                CharonHub.StartLocation = event.getBlock().getLocation();
                ParkourManager.adminSet.remove(event.getPlayer());
            } else if (ParkourManager.adminSet.get(event.getPlayer()) == 2){
                //放end
                CharonHub.instance.getConfig().set("EndX", event.getBlock().getX());
                CharonHub.instance.getConfig().set("EndY", event.getBlock().getY());
                CharonHub.instance.getConfig().set("EndZ", event.getBlock().getZ());
                CharonHub.instance.saveConfig();
                event.getPlayer().sendMessage("§b§l已设置终点");
                event.setCancelled(true);
                CharonHub.EndLocation = event.getBlock().getLocation();
                ParkourManager.adminSet.remove(event.getPlayer());
            }
        }
    }

    @EventHandler
    public void onPlaceBlock(BlockPlaceEvent event){
        if (ParkourManager.parkourPlayers.containsKey(event.getPlayer())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onPlayerQuitServer(PlayerQuitEvent event){
        ParkourManager.playerParkourRecord.remove(event.getPlayer());
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event){
        if (event.getTo().getY() <= 0){
            event.getPlayer().teleport(event.getPlayer().getWorld().getSpawnLocation());
        }
    }

    @EventHandler
    public void onPlayerMoveIce(PlayerMoveEvent event){
        Block block  = event.getPlayer().getWorld().getBlockAt(event.getTo().clone().add(0, -1, 0));
        if (block.getType().equals(Material.ICE)){
            event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 9999999, 2), true);
        } else if (block.getType().equals(Material.AIR)){
            return;
        } else {
            event.getPlayer().removePotionEffect(PotionEffectType.SPEED);
            event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 9999999, 0), true);
        }
    }

    @EventHandler
    public void onEntitySpawn(EntitySpawnEvent event){
        event.setCancelled(true);
    }

    @EventHandler
    public void onPlayerJoinServerSetRecord(PlayerAfterLoginListener event){
        BukkitRunnable task = new BukkitRunnable() {
            @SneakyThrows
            @Override
            public void run() {
                SqlManager sqlManager = new SqlManager("charonmc");
                Object id = sqlManager.createQuery()
                        .inTable("players")
                        .selectColumns("player_id")
                        .addCondition("player_name", event.getPlayer().getName())
                        .build()
                        .execute()
                        .first();
                ResultSet set = sqlManager.createQuery()
                        .inTable("parkour_1")
                        .selectColumns("score")
                        .addCondition("player_id", id)
                        .build()
                        .execute()
                        .getResult();
                if (set.next()){
                    int tickTime = set.getInt(1);
                    ParkourManager.playerParkourRecord.put(event.getPlayer(), tickTime);
                } else {
                    sqlManager.createInsert()
                            .inTable("parkour_1")
                            .addColumnNames(new String[]{"player_id", "score"})
                            .addParams(new Object[]{id, 0})
                            .build()
                            .execute();
                    ParkourManager.playerParkourRecord.put(event.getPlayer(), 0);
                }
                sqlManager.close();
            }
        };
        task.runTaskAsynchronously(CharonHub.instance);
    }
}
